import type { MenuDataItem } from '@ant-design/pro-layout';
export interface BackMenu {
  id: number;
  parent_id: number;
  name: string;
  path: string;
  component?: string | null; // 目录节点 component 为 null
  icon?: string;
  redirect?: string;
}
/**
 * 1. 把扁平数组 → 树
 */
function flatToTree<T extends { id: number; parent_id: number; sort?: number }>(
  arr: T[],
): T[] {
  const map = new Map<number, T & { children?: T[] }>();
  const result: T[] = [];

  // 先放入 map
  arr.forEach((item) => map.set(item.id, { ...item, children: [] }));

  // 再挂到 parent 下
  arr.forEach((item) => {
    const node = map.get(item.id)!;
    if (item.parent_id === 0) result.push(node);
    else {
      const parent = map.get(item.parent_id);
      if (parent) {
        (parent.children = parent.children || []).push(node);
      } else {
        console.warn('【孤儿节点】', item); // ③ 一旦丢节点，这里会打印
      }
    }
  });
  const sortFn = (a: any, b: any) => (a.sort ?? 0) - (b.sort ?? 0);
  result.sort(sortFn);
  result.forEach((item) => item.children?.sort(sortFn));
  return result;
}

/**
 * 2. 生成 ProLayout 需要的 menuData
 */
export function backMenuToMenuData(list: BackMenu[]): MenuDataItem[] {
  const tree = flatToTree(list);
  function trav(data: BackMenu[]): MenuDataItem[] {
    return data.map((item) => ({
      path: item.path,
      name: item.name,
      icon: item.icon,
      redirect: item.redirect,
      children: item.children?.length ? trav(item.children) : undefined,
    }));
  }
  return trav(tree);
}

/**
 * 3. 生成 Umi 路由（剔除 component 为 null 的目录节点）
 */
export function backMenuToRoutes(list: BackMenu[]) {
  const tree = flatToTree(list);
  function trav(data: BackMenu[]): any[] {
    return data.map((item): RouteObject => {
      const route: RouteObject = { path: item.path };
      /* ① 看看到底有没有 component */
      // 1. 有组件 → 挂 lazy
      if (item.component) {
        route.element= () => import(`@/pages/${item.component.replace('./','')}/index.tsx`);
      }

      // 2. 有孩子 → 挂 children
      if (item.children?.length) {
        route.children = trav(item.children);
      }

      // 3. 额外信息放 handle（可选）
      route.handle = {
        name: item.name,
        icon:item.icon,
      }
        return route;
    });
  }
  return trav(tree);
}
